package com.jzt.qf.https;


import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jzt.qf.beans.*;
import com.jzt.qf.beans.jztBean.TokenBean;
import com.jzt.qf.dao.JztTokenDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 浙江
 * key:RKyQQYK7miaeFGsGPnPvjS4q
 * keypassword:K6WFe8UZGIJvsM55Vg3TQ8YCgkaixEWI
 */
@Component
@Slf4j
public class JztApi {
    TimedCache<String, TokenBean> tokenCache = CacheUtil.newTimedCache(2000000);
    //正式环境
    private String tokenUrl = "https://api.56jzt.com/gateway/admin/client/token";
    private String HTTPURL = "https://api.56jzt.com/gateway/api-general/v1/";
    //测试环境
//    private String tokenUrl = "http://219.139.241.75:8889/gateway/admin/client/token";
//    private String HTTPURL = "https://api.56jzt.com/gateway/api-general/v1/";
    private String client_id = "RKyQQYK7miaeFGsGPnPvjS4q";
    private String client_secret = "K6WFe8UZGIJvsM55Vg3TQ8YCgkaixEWI";

    /**
     * http请求
     * 新的请求方法.需要Token
     *
     * @return codeData 接口调用返回数据
     */
    public HttpResult HttpRequest(UploadBase uploadBase) {
        String accessToken = getToken().getData().getAccess_token();
        if (accessToken.isEmpty()) {
            log.error("获取token失败");
            return null;
        }
        //TODO 九州通Api接口调用方式发生了变化,现在需要传递token,body里面锁需要的数据也不一样,
        //TODO 为了兼容之前开发的程序,所以只在http请求方面进行更改,将uploadBase 改成uploadBase2 进行上传
        UploadBase2 uploadBase2 = new UploadBase2();
        uploadBase2.setFunc_type(uploadBase.getFuncType()).setJson_data(uploadBase.getJsondata());
        String url = HTTPURL + uploadBase.getCallCategory();
        log.info("访问路径" + url);
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Content-Type", "application/json");
        headerMap.put("Authorization", "Bearer " + accessToken);
        String result = HttpRequest.post(url).addHeaders(headerMap).body(JSON.toJSONString(uploadBase2)).execute().body();
        String resultData = result;
        log.info(result);
        HttpResult httpResult = null;
        try {
            //这里九州通上传接口和下载数据接口返回的结果集不一样,所以要进行判断,如果是上传接口
            if (uploadBase.getFuncType().equals("saveData")) {
                HttpResult_Upload httpResultUpload = JSON.parseObject(result, HttpResult_Upload.class);
                if (httpResultUpload.getCode() == 0) {
                    httpResult = new HttpResult(true, httpResultUpload.getMessage(), null);
                } else {
                    httpResult = new HttpResult(false, httpResultUpload.getMessage(), null);
                }
            } else {
                HttpResult_Upload httpResultUpload = JSON.parseObject(result, HttpResult_Upload.class);
                if (httpResultUpload.getData().size() > 0) {
                    httpResult = new HttpResult(true, httpResultUpload.getMessage(), httpResultUpload.getData());
                } else {
                    httpResult = new HttpResult(false, httpResultUpload.getMessage(), httpResultUpload.getData());
                }
            }

        } catch (Exception e) {
            log.error("接口返回数据解析异常" + resultData);
            httpResult = new HttpResult(false, resultData, null);
        }
        return httpResult;
    }

    @Value("${jzt.name}")
    private String jztName;
    @Resource
    private JztTokenDao jztTokenDao;

    public TokenBean getToken() {
        JztToken jztToken = jztTokenDao.getTokenByJztName(jztName);
        if (BeanUtil.isNotEmpty(jztToken)) {
            TokenBean token = new TokenBean();
            TokenBean.DataBean dataBean = new TokenBean.DataBean();
            dataBean.setAccess_token(jztToken.getToken());
            token.setData(dataBean);
            return token;
        } else {
            String url = tokenUrl + "?client_id=" + client_id + "&client_secret=" + client_secret;
            String body = HttpRequest.get(url).execute().body();
            log.info(body);
            TokenBean tokenBean = JSONObject.parseObject(body, TokenBean.class);
            JztToken jztToken1 = new JztToken();
            jztToken1.setJztName(jztName);
            jztToken1.setToken(tokenBean.getData().getAccess_token());
            jztTokenDao.addToken(jztToken1);
            return tokenBean;
        }
    }

}
